<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : User session library
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class User_session {

  private $ci;

  public function __construct() {
    $this->ci = & get_instance();
  }

  // Sets the user id in the session
  private function set_signin_user($user_id = NULL) {
    if (!empty($user_id) && is_numeric($user_id)) {
      $this->ci->session->set_userdata('_INNOTWEETS_USER_', $user_id);
      return TRUE;
    }
    return FALSE;
  }

  // Gets the saved user id in the session
  // ie. current signed in user id
  private function get_signin_user() {
    $user_id = $this->ci->session->userdata('_INNOTWEETS_USER_');
    if (!empty($user_id) && is_numeric($user_id)) {
      return $user_id;
    }
    return FALSE;
  }

  // Unset all current user session
  private function del_signin_user() {
    $this->ci->session->set_userdata('_INNOTWEETS_USER_', '');
    $this->ci->session->unset_userdata('_INNOTWEETS_USER_');
    $this->ci->session->sess_destroy();
  }

  // Signing in the user
  // Calls the set user session method
  public function signin($username = NULL, $enc_password = NULL) {
    if (!empty($username) && !empty($enc_password) && ctype_alnum($enc_password)) {
      $get_user_by_password = $this->ci->user_model->get_user_by_password($username, $enc_password);
      if ($get_user_by_password['status'] == 1 && !empty($get_user_by_password['result'])) {
        return $this->set_signin_user($get_user_by_password['result']['user_id']);
      }
    }
  }

  // Signing out the user
  // Calls the clear user session method
  public function signout() {
    $this->del_signin_user();
  }

  // Returs user data if valid session
  // Update the current user last activity time
  public function signuser($set_online = TRUE, $set_offline = TRUE) {
    $user_id = $this->get_signin_user();
    if (!empty($user_id) && is_numeric($user_id)) {
      $get_user_by_id = $this->ci->user_model->get_user_by_id($user_id);
      if ($get_user_by_id['status'] == 1 && !empty($get_user_by_id['result'])) {
        if ($set_online) {
          $this->ci->user_model->update_online($user_id); // Go Online
        } else {
          if ($set_offline) {
            $this->ci->user_model->update_online($user_id, TRUE); // Go Offline
          }
        }
        return $get_user_by_id['result'];
      }
    }
    return FALSE;
  }

}

?>
